<template>
  <div class="pickup-page">
    <div class="pickup-header">
      <h1>取餐管理</h1>
      <p>管理客户取餐订单，实时更新取餐状态</p>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <el-form :model="searchForm" inline>
        <el-form-item label="订单号">
          <el-input 
            v-model="searchForm.orderNo" 
            placeholder="输入订单号搜索"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        <el-form-item label="桌号">
          <el-input 
            v-model="searchForm.tableNo" 
            placeholder="输入桌号搜索"
            style="width: 150px"
            clearable
          />
        </el-form-item>
        <el-form-item label="取餐状态">
          <el-select v-model="searchForm.status" placeholder="全部状态" style="width: 150px" clearable>
            <el-option label="待取餐" value="pending" />
            <el-option label="已取餐" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchOrders">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card pending">
            <div class="stat-icon">
              <el-icon size="24"><Clock /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ stats.pending }}</div>
              <div class="stat-label">待取餐</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card completed">
            <div class="stat-icon">
              <el-icon size="24"><Check /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ stats.completed }}</div>
              <div class="stat-label">已取餐</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card today">
            <div class="stat-icon">
              <el-icon size="24"><Calendar /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ stats.today }}</div>
              <div class="stat-label">今日取餐</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card total">
            <div class="stat-icon">
              <el-icon size="24"><Document /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ stats.total }}</div>
              <div class="stat-label">总订单</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 订单列表 -->
    <div class="orders-section">
      <div class="section-header">
        <h2>取餐订单列表</h2>
        <div class="header-actions">
          <el-button type="success" @click="batchComplete" :disabled="!hasSelectedOrders">
            <el-icon><Check /></el-icon>
            批量完成取餐
          </el-button>
          <el-button type="primary" @click="refreshOrders">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>

      <el-table 
        :data="ordersList" 
        border 
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="订单号" width="180" />
        <el-table-column prop="tableNo" label="桌号" width="80" />
        <el-table-column prop="customerName" label="客户姓名" width="120" />
        <el-table-column prop="orderTime" label="下单时间" width="180" />
        <el-table-column prop="estimatedTime" label="预计完成时间" width="180" />
        <el-table-column prop="status" label="取餐状态" width="100">
          <template #default="scope">
            <el-tag 
              :type="getStatusType(scope.row.status)"
              :effect="scope.row.status === 'pending' ? 'dark' : 'light'"
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="订单金额" width="120">
          <template #default="scope">
            ¥{{ scope.row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button 
              v-if="scope.row.status === 'pending'"
              type="success" 
              size="small" 
              @click="completePickup(scope.row)"
            >
              完成取餐
            </el-button>
            <el-button 
              type="primary" 
              size="small" 
              @click="viewOrderDetail(scope.row)"
            >
              查看详情
            </el-button>
            <el-button 
              v-if="scope.row.status === 'pending'"
              type="warning" 
              size="small" 
              @click="cancelOrder(scope.row)"
            >
              取消订单
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog 
      v-model="orderDetailVisible" 
      title="订单详情" 
      width="800px"
      :before-close="closeOrderDetail"
    >
      <div v-if="currentOrder" class="order-detail">
        <div class="detail-section">
          <h3>基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="订单号">{{ currentOrder.orderNo }}</el-descriptions-item>
            <el-descriptions-item label="桌号">{{ currentOrder.tableNo }}</el-descriptions-item>
            <el-descriptions-item label="客户姓名">{{ currentOrder.customerName }}</el-descriptions-item>
            <el-descriptions-item label="下单时间">{{ currentOrder.orderTime }}</el-descriptions-item>
            <el-descriptions-item label="预计完成时间">{{ currentOrder.estimatedTime }}</el-descriptions-item>
            <el-descriptions-item label="取餐状态">
              <el-tag :type="getStatusType(currentOrder.status)">
                {{ getStatusText(currentOrder.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="订单金额">¥{{ currentOrder.totalAmount }}</el-descriptions-item>
            <el-descriptions-item label="备注">{{ currentOrder.remark || '无' }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="detail-section">
          <h3>菜品明细</h3>
          <el-table :data="currentOrder.dishes" border style="width: 100%">
            <el-table-column prop="dishName" label="菜品名称" />
            <el-table-column prop="quantity" label="数量" width="80" />
            <el-table-column prop="unitPrice" label="单价" width="100">
              <template #default="scope">
                ¥{{ scope.row.unitPrice }}
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="小计" width="100">
              <template #default="scope">
                ¥{{ scope.row.amount }}
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" />
          </el-table>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeOrderDetail">关闭</el-button>
          <el-button 
            v-if="currentOrder && currentOrder.status === 'pending'"
            type="success" 
            @click="completePickup(currentOrder)"
          >
            完成取餐
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  tableNo: '',
  status: '',
  dateRange: []
})

// 统计数据
const stats = reactive({
  pending: 0,
  completed: 0,
  today: 0,
  total: 0
})

// 订单列表
const ordersList = ref([])
const selectedOrders = ref([])
const loading = ref(false)

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 订单详情
const orderDetailVisible = ref(false)
const currentOrder = ref(null)

// 计算属性
const hasSelectedOrders = computed(() => selectedOrders.value.length > 0)

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    pending: 'warning',
    completed: 'success',
    cancelled: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '待取餐',
    completed: '已取餐',
    cancelled: '已取消'
  }
  return statusMap[status] || '未知'
}

// 搜索订单
const searchOrders = () => {
  pagination.currentPage = 1
  loadOrders()
}

// 重置搜索
const resetSearch = () => {
  searchForm.orderNo = ''
  searchForm.tableNo = ''
  searchForm.status = ''
  searchForm.dateRange = []
  searchOrders()
}

// 加载订单数据
const loadOrders = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟数据
    const mockOrders = []
    for (let i = 1; i <= 20; i++) {
      const status = ['pending', 'completed', 'cancelled'][Math.floor(Math.random() * 3)]
      mockOrders.push({
        id: i,
        orderNo: `ORD${Date.now().toString().slice(-8)}${i.toString().padStart(2, '0')}`,
        tableNo: `A${i % 10 + 1}`,
        customerName: `客户${i}`,
        orderTime: '2024-01-15 12:30:00',
        estimatedTime: '2024-01-15 13:00:00',
        status,
        totalAmount: (Math.random() * 200 + 50).toFixed(2),
        remark: i % 3 === 0 ? '请尽快完成' : '',
        dishes: [
          {
            dishName: '农家小炒肉',
            quantity: 2,
            unitPrice: 12.50,
            amount: 25.00,
            remark: ''
          },
          {
            dishName: '宫保鸡丁',
            quantity: 1,
            unitPrice: 18.00,
            amount: 18.00,
            remark: '不要太辣'
          }
        ]
      })
    }
    
    ordersList.value = mockOrders
    pagination.total = 100
    
    // 更新统计数据
    updateStats()
  } catch (error) {
    ElMessage.error('加载订单数据失败')
  } finally {
    loading.value = false
  }
}

// 更新统计数据
const updateStats = () => {
  const pending = ordersList.value.filter(order => order.status === 'pending').length
  const completed = ordersList.value.filter(order => order.status === 'completed').length
  const total = ordersList.value.length
  
  stats.pending = pending
  stats.completed = completed
  stats.total = total
  stats.today = Math.floor(Math.random() * 50) + 20 // 模拟今日数据
}

// 完成取餐
const completePickup = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确定要将订单 ${order.orderNo} 标记为已取餐吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟API调用
    order.status = 'completed'
    ElMessage.success('取餐状态更新成功')
    updateStats()
  } catch {
    // 用户取消
  }
}

// 批量完成取餐
const batchComplete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要将选中的 ${selectedOrders.value.length} 个订单标记为已取餐吗？`,
      '批量操作确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 批量更新状态
    selectedOrders.value.forEach(order => {
      order.status = 'completed'
    })
    
    ElMessage.success(`成功完成 ${selectedOrders.value.length} 个订单的取餐`)
    selectedOrders.value = []
    updateStats()
  } catch {
    // 用户取消
  }
}

// 取消订单
const cancelOrder = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消订单 ${order.orderNo} 吗？`,
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟API调用
    order.status = 'cancelled'
    ElMessage.success('订单取消成功')
    updateStats()
  } catch {
    // 用户取消
  }
}

// 查看订单详情
const viewOrderDetail = (order) => {
  currentOrder.value = order
  orderDetailVisible.value = true
}

// 关闭订单详情
const closeOrderDetail = () => {
  orderDetailVisible.value = false
  currentOrder.value = null
}

// 刷新订单
const refreshOrders = () => {
  loadOrders()
}

// 选择变化处理
const handleSelectionChange = (selection) => {
  selectedOrders.value = selection
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadOrders()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadOrders()
}

// 页面加载时初始化数据
onMounted(() => {
  loadOrders()
})
</script>

<style scoped>
.pickup-page {
  padding: 20px;
}

.pickup-header {
  text-align: center;
  margin-bottom: 30px;
}

.pickup-header h1 {
  font-size: 28px;
  color: #303133;
  margin-bottom: 8px;
}

.pickup-header p {
  font-size: 16px;
  color: #909399;
}

.search-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
}

.stat-card.pending .stat-icon {
  background: linear-gradient(135deg, #ff6b6b, #ee5a24);
}

.stat-card.completed .stat-icon {
  background: linear-gradient(135deg, #1dd1a1, #10ac84);
}

.stat-card.today .stat-icon {
  background: linear-gradient(135deg, #48dbfb, #0abde3);
}

.stat-card.total .stat-icon {
  background: linear-gradient(135deg, #5f27cd, #341f97);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.orders-section {
  background: #fff;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.section-header h2 {
  font-size: 20px;
  color: #303133;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.order-detail {
  max-height: 500px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h3 {
  font-size: 16px;
  color: #303133;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e4e7ed;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style> 